﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Memo.Electricity.Engine;

namespace Memo.Electricity.Game
{
	public class CSwitch : MemoBehaviour
	{
		public GameObject Target { get => mTarget; }

		[SerializeField] private GameObject mTarget;
		[SerializeField] private Sprite mActiveSprite;
		[SerializeField] private Sprite mUnactiveSprite;

		private CRelay mRelayHandle;
		private ISwitchable mSwitchHandle;
		private SpriteRenderer mSpriteRenderer;

		private void Awake()
		{
			mSpriteRenderer = GetComponent<SpriteRenderer>();
			mSwitchHandle = mTarget?.GetComponent<ISwitchable>();
			if (mSwitchHandle == null)
			{
				Debug.LogError("Switch的Target必须为ISwitchable");
			}
		}

		private void OnTriggerEnter2D(Collider2D collision)
		{
			if (mRelayHandle == null)
			{
				mRelayHandle = collision.GetComponent<CRelay>();
				if (mRelayHandle && !collision.isTrigger)
				{
					mRelayHandle.GetComponent<Animator>().SetBool("IsCharging", true);
					mSwitchHandle.SwitchOn();
					GetComponent<Animator>().SetBool("IsActive", true);
				}
				else
				{
					mRelayHandle = null;
				}
			}
		}

		private void OnTriggerExit2D(Collider2D collision)
		{
			if (mRelayHandle)
			{
				if (collision.GetComponent<CRelay>() == mRelayHandle)
				{
					mRelayHandle.GetComponent<Animator>().SetBool("IsCharging", false);
					mRelayHandle = null;
					GetComponent<Animator>().SetBool("IsActive", false);
					mSwitchHandle.SwitchOff();
					mSpriteRenderer.sprite = mUnactiveSprite;
				}
			}

		}


	}
}
